<template>
  <div class="personnel-record-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="search-item">
              <span class="label">所属小区</span>
              <el-input
                  v-model="searchForm.communityName"
                  placeholder="请输入小区名称"
                  clearable
                  class="search-input"
              />
            </div>
          </el-col>
          <el-col :span="6">
            <div class="search-item">
              <span class="label">出入闸机</span>
              <el-input
                  v-model="searchForm.gateDevice"
                  placeholder="请输入闸机名称"
                  clearable
                  class="search-input"
              />
            </div>
          </el-col>
          <el-col :span="6">
            <div class="search-item">
              <span class="label">人员姓名</span>
              <el-input
                  v-model="searchForm.name"
                  placeholder="请输入人员姓名"
                  clearable
                  class="search-input"
              />
            </div>
          </el-col>
          <el-col :span="6">
            <div class="search-actions">
              <el-button type="primary" @click="handleSearch" class="search-btn">
                查询
              </el-button>
              <el-button @click="handleReset" class="reset-btn">
                重置
              </el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
          :data="tableData"
          stripe
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
        />
        <el-table-column
            prop="name"
            label="姓名"
            width="80"
            align="center"
        />
        <el-table-column
            prop="phone"
            label="手机号"
            width="110"
            align="center"
        />
        <el-table-column
            prop="gateDevice"
            label="出入闸机"
            width="110"
            align="center"
        />
        <el-table-column
            prop="accessMethod"
            label="出入方式"
            width="80"
            align="center"
        >
          <template #default="scope">
            <el-tag
                :type="scope.row.accessMethod === '人脸识别' ? 'success' : 'primary'"
                size="small"
            >
              {{ scope.row.accessMethod }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="进入时间"
            width="120"
            align="center"
        >
          <template #default="scope">
            {{ formatDateTime(scope.row.entryTime) }}
          </template>
        </el-table-column>
        <el-table-column
            label="离开时间"
            width="120"
            align="center"
        >
          <template #default="scope">
            {{ scope.row.exitTime ? formatDateTime(scope.row.exitTime) : '尚未出场' }}
          </template>
        </el-table-column>
        <el-table-column
            label="出入小区"
            width="100"
            align="center"
        >
          <template #default="scope">
            {{ scope.row.communityName|| '-' }}
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="80"
            align="center"
            fixed="right"
        >
          <template #default="scope">
            <el-button
                type="primary"
                link
                size="small"
                @click="handleView(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElTag } from 'element-plus'
import { selectAllPersonnelRecords } from '@/api/owner/record'
import { useRouter } from 'vue-router'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  communityName: '',
  gateDevice: '',
  name: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 5
})

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 计算停留时长
const formatStayDuration = (entryTime, exitTime) => {
  if (!entryTime) return '-'
  if (!exitTime) return '进行中'

  const entry = new Date(entryTime)
  const exit = new Date(exitTime)
  const duration = exit - entry

  const hours = Math.floor(duration / (1000 * 60 * 60))
  const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60))

  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  initData()
}

// 重置处理
const handleReset = () => {
  Object.assign(searchForm, {
    communityName: '',
    gateDevice: '',
    name: ''
  })
  pagination.currentPage = 1
  initData()
}

// 查看详情
const handleView = (row) => {
  console.log('=== 人员记录详情 ===')
  console.log('点击的行数据:', row)

  // 构建查询参数
  const queryParams = {
    personnelId: row.personnelId || '',
    name: row.name || '',
    phone: row.phone || '',
    gateDevice: row.gateDevice || '',
    accessMethod: row.accessMethod || '',
    entryTime: row.entryTime || '',
    exitTime: row.exitTime || '',
    community: row.communityName|| '',
    photo: row.photo || null
  }

  console.log('查询参数:', queryParams)

  router.push({
    path: '/record/personnelDetail',
    query: queryParams
  })
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  initData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  initData()
}

const initData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }
debugger
    // 添加搜索条件
    if (searchForm.communityName) {
      params.communityName = searchForm.communityName
    }
    if (searchForm.gateDevice) params.gateDevice = searchForm.gateDevice
    if (searchForm.name) params.name = searchForm.name

    console.log('查询参数:', params)

    const response = await selectAllPersonnelRecords(params)

    tableData.value = response.rows || []
    pagination.total = response.total || 0

    console.log('完整API响应:', response)
    ElMessage.success(response.msg || '查询成功')

  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error(error.message||error.response.data?.msg||'查询失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 初始化加载数据
onMounted(() => {
  initData()
})
</script>

<style scoped>
.personnel-record-container {
  padding: 16px 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 50px);
}

.search-card {
  margin-bottom: 16px;
  border-radius: 4px;
}

.search-form {
  padding: 16px 0;
}

.search-item {
  display: flex;
  align-items: center;
}

.search-item .label {
  width: 80px;
  text-align: right;
  margin-right: 12px;
  font-size: 14px;
  color: #333;
  flex-shrink: 0;
}

.search-input {
  flex: 1;
}

.search-actions {
  display: flex;
  align-items: center;
  height: 32px;
  padding-left: 12px;
}

.search-btn,
.reset-btn {
  margin-right: 12px;
}

.table-card {
  border-radius: 4px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  padding: 16px 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

/* 状态标签样式 */
:deep(.el-tag) {
  border: none;
  font-weight: 500;
}
</style>